package com.vichat.gps.controller;

import com.alibaba.fastjson.JSONObject;
import com.vichat.business.service.IVcAlarmService;
import com.vichat.common.constant.I18nConstant;
import com.vichat.common.exception.ViChatException;
import com.vichat.common.util.DateUtil;
import com.vichat.common.util.I18NUtil;
import com.vichat.common.vo.Json;
import com.vichat.gps.entity.LocationData;
import com.vichat.gps.entity.LocationDataLog;
import com.vichat.gps.service.IGpsService;
import com.vichat.user.cache.I18nMappingCache;
import com.vichat.user.controller.BaseController;
import com.vichat.user.entity.UserBasic;
import com.vichat.user.service.ISystemMessageService;
import com.vichat.user.service.IUserService;
import com.vichat.user.vo.RequestParamsVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ranjx on 2017/11/20.
 */
@Controller
@RequestMapping("/gpsApi")
public class GpsApiController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(GpsApiController.class);
    ExecutorService tp = Executors.newCachedThreadPool();
    public static boolean threadFlag = false;
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;

    @Autowired
    private IGpsService gpsService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IVcAlarmService alarmService;
    @Autowired
    private ISystemMessageService systemMessageService;
    @Autowired
    private I18nMappingCache i18nMappingCache;


    private static boolean isStartGpsSaveThread = false;
    /**
     * 上传gps定位信息
     *
     * @param locData
     * @return
     */
    @RequestMapping("/uploadGps")
    @ResponseBody
    public Json uploadGps(@RequestBody List<LocationData> locData) {
        Json json = new Json();
        try {

            if (!locData.isEmpty()) {
                UploadGpsThread thread = new UploadGpsThread(userService,gpsService,GpsThreadInit.gpsAppCache,locData);
                FenceGpsProcessThread process = new FenceGpsProcessThread(userService,alarmService,systemMessageService,GpsThreadInit.gpsAppCache,locData,i18nMappingCache);
                tp.execute(thread);
                tp.execute(process);
            }
            json.setSuccess(true);
        } catch (Exception e) {
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * 上传gps定位信息
     *
     * @param locData
     * @return
     */
    @RequestMapping("/uploadGpsAbTest")
    @ResponseBody
    public Json uploadGpsTest(@RequestBody List<LocationData> locData) {
        Json json = new Json();
        try {

            if (!locData.isEmpty()) {
                for (int i = 0 ;i< locData.size();i++){
                    locData.get(i).setLocTime(System.currentTimeMillis()+i);
                }
                UploadGpsThread thread = new UploadGpsThread(userService,gpsService,GpsThreadInit.gpsAppCache,locData);
                tp.execute(thread);
            }
            json.setSuccess(true);
        } catch (Exception e) {
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }



    /**
     * 获取所有人员当天最新定位信息
     *
     * @param paramsVO
     * @return
     */
    @RequestMapping("/getUserLocations")
    @ResponseBody
    public Json getUserLocations(@RequestBody RequestParamsVO paramsVO) {
        Json json = new Json();
        try {

            checkToken(paramsVO);

            UserBasic userBasicFDB = userService.getUserBasicByUid(paramsVO.getUid());
            if (userBasicFDB == null) {
                // 没有该用户信息，请确认UID参数
                String errorMsg = I18NUtil.getMessage("GpsApiController.uploadLocDevice.error_userNotExist", null, Locale.CHINA);
                throw new ViChatException(I18nConstant.error_userNotExist, errorMsg);
            }
            LocationData queryBean = new LocationData();
            queryBean.setPartyId(userBasicFDB.getPartyId());
            queryBean.setOrgId(userBasicFDB.getOrgId());
            queryBean.setOrgCode(userBasicFDB.getOrgCode());
            Date startDate = null;
            if(paramsVO.getDate() !=null){
                startDate= DateUtil.getDateByString(paramsVO.getDate());//"yyyy-MM-dd HH:mm:ss"
            }
            List<LocationDataLog> locationDatas = gpsService.queryLocationDatas(queryBean,startDate,null);
            json.setObj(locationDatas);
            json.setSuccess(true);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * 根据UID获取用户轨迹
     *
     * @param paramsVO
     * @return
     */
    @RequestMapping("/getLocationsByUid")
    @ResponseBody
    public Json getLocationByUid(@RequestBody RequestParamsVO paramsVO) {
        Json json = new Json();
        try {
            checkToken(paramsVO);
            List<Long> uids = paramsVO.getUids();
            if(uids == null || uids.size() == 0){
                throw new Exception("uids is required");
            }

            long uid = uids.get(0);//只取第一个
            UserBasic sessionUser = userService.getUserBasicByUid(paramsVO.getUid());
            UserBasic userBasicFDB = userService.getUserBasicByUid(uid);
            if (userBasicFDB == null) {
                String errorMsg = I18NUtil.getMessage("GpsApiController.uploadLocDevice.error_userNotExist", null, Locale.CHINA);
                throw new ViChatException(I18nConstant.error_userNotExist, errorMsg);
            }
            if (userBasicFDB.getPartyId().longValue() == sessionUser.getPartyId().longValue()) {
                List<LocationData> locationDatas = gpsService.getLocationDatasByUid(userBasicFDB.getUid(),paramsVO.getDate());
                json.setObj(locationDatas);
                json.setSuccess(true);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


}
